package jee.boot.common.interceptor;

import jee.boot.common.utils.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebInterceptorConfigurator extends WebMvcConfigurationSupport  {
    private Logger logger = LoggerFactory.getLogger(WebInterceptorConfigurator.class);
	public void addInterceptors(InterceptorRegistry registry) {
	    // 查询系统中所有的定义的web拦截器
        String[] interceptors = SpringContextHolder.getApplicationContext().getBeanNamesForType(HandlerInterceptor.class);
        if(interceptors!=null && interceptors.length>0 ){
            for(String beanName:interceptors){
                registry.addInterceptor(SpringContextHolder.getBean(beanName)).addPathPatterns("/**");
                logger.info("注册web拦截器: "+beanName);
            }

        }
		super.addInterceptors(registry);
	}

    /**
     *  覆盖父类方法,解决静态资源无法访问的问题
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");
        super.addResourceHandlers(registry);
    }

}
